﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronOne.SalesOne.BusinessObjects;
using System.Web.UI.WebControls;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;


namespace IronOne.SalesOne.DataObjects
{
    public class LinqJob
    {
        public int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]);

        public bool UpdateSchedule(BatchJob job, string currentUser)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                if(db.uspJobSchedule(job.Schedule_Name, 
                    (byte)job.Enabled, 
                    job.FreqType, 
                    job.FreqInterval, 
                    job.FreqSubdayType, 
                    job.FreqSubdayInterval, 
                    job.FreqRelativeInterval, 
                    job.FreqRecurrenceFactor, 
                    job.ActiveStartDate, 
                    job.ActiveEndDate, 
                    job.ActiveStartTime, 
                    job.ActiveEndTime,
                    currentUser) == 0)
                    return true;

                return false;
            }
            
        }

        public void GetSchedule(string name)
        {
        }

        public List<ListItem> GetAvailableJobs()
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                return (from jobs in db.BatchJobEntities
                       select new ListItem
                       {
                           Text = jobs.JobId,
                           Value = jobs.ScheduleId
                       }).ToList();
            }
        }

        public BatchJob GetAvailableJobs(string scheduleName)
        {
            BatchJob job = new BatchJob();
            SqlDataReader reader = null;
            SqlConnection conn = null;
            try
            {
                //conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                string connectionStringName = ConfigurationManager.AppSettings.Get("ConnectionStringName");
                conn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString);
                conn.Open();
                SqlCommand comm = new SqlCommand("uspGetJobSchdule", conn);

                comm.Parameters.Add(new SqlParameter("@_schdule_name", scheduleName));
                comm.CommandType = System.Data.CommandType.StoredProcedure;
                reader = comm.ExecuteReader();

                if (reader.Read())
                    job = Mapper.ToBatchJobObject(reader);
                
            }
            catch { }
            finally
            {
                if(reader != null)
                    reader.Close();
                if(conn != null)
                    conn.Close();
            }
            return job;
        }

        public List<JobHistory> getHistoryForJob(string jobId, int pageNo)
        {
            using (SOSysDataDataContext db = SysDataContextFactory.CreateContext())
            {
                var query = from history in db.sysjobhistoryEntities
                            where history.job_id == ((from job in db.sysjobEntities
                                                      where job.name == jobId
                                                      select job.job_id).SingleOrDefault())
                            orderby history.run_date descending
                            select new JobHistory
                            {
                                StartTime = history.run_date.ToString().Length == 8 && history.run_time.ToString().Length == 6 ? new DateTime(int.Parse(history.run_date.ToString().Substring(0, 4)), int.Parse(history.run_date.ToString().Substring(4, 2)), int.Parse(history.run_date.ToString().Substring(6, 2)), int.Parse(history.run_time.ToString().Substring(0, 2)), int.Parse(history.run_time.ToString().Substring(2, 2)), int.Parse(history.run_time.ToString().Substring(4, 2))) : new DateTime(1753,1,1),
                                Duration = history.run_duration,
                                Status = history.message
                            };
                //query = query.OrderByDescending(p => p.StartTime);

                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);


                return pageData.ToList();                
            }
            
        }
    }
}
